<template>

    <div class="padding_box">
        <div class="top_box">
            <div class="page-title font-weight-500">考勤设置
            </div>
        </div>
      
            <div class="app-container">
                <el-form ref="form"
                         :model="form">
						 <el-form-item label="打卡距离">
						     <el-input clearable
						               v-model="form.distance"
						               placeholder="请输入打卡距离(米)"></el-input>
						 </el-form-item>
                    <el-form-item label="学校位置"
                                  prop="address">
                        <el-autocomplete v-model="form.address"
                                         style="width:100%;"
                                         popper-class="autoAddressClass"
                                         :fetch-suggestions="querySearchAsync"
                                         :trigger-on-focus="false"
                                         placeholder="详细地址"
                                         clearable
                                         @select="handleSelect">
                            <template slot-scope="{ item }">
                                <i class="el-icon-search fl mgr10" />
                                <div style="overflow:hidden;">
                                    <div class="title">{{ item.title }}</div>
                                    <span class="address ellipsis">{{ item.address }}</span>
                                </div>
                            </template>
                        </el-autocomplete>
                    </el-form-item>
                    <el-form-item label="">
                        <div id="map-container"
                             style="width:100%;height:400px;" />
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary"
                                   @click="onSubmit">提交</el-button>
                        <el-button>取消</el-button>
                    </el-form-item>
                </el-form>
            </div>
       

    </div>
</template>

<script>
import bus from '@/common/bus';
import Axios from 'axios';
import axios from '@/utils/axios.js';
var mytheme = require('@/utils/echarts/macarons.json')
import * as echarts from 'echarts';
import loadBMap from '@/utils/loadBMap.js'

export default {
    name: 'dashboard',
    data() {
        return {
			info:{},
			distance:"",
            addVisible: true,
            form: {
				distance:"",
                address: '', // 详细地址
                addrPoint: { // 详细地址经纬度
                    lng: 0,
                    lat: 0
                }
            },
            map: '', // 地图实例
            mk: '', // Marker实例
            locationPoint: null,
            queryTime: '',
            queryData: {
                startTime: '',
                endTime: '',
            },
            integralLoading: true,
            orderTransactionLoading: true,
            timer: '',
            lineChart: '',
            lineAndBarChart: '',
            memberAndUserData: {
                memberCount: 0,
                merchantCount: 0,
            },
            orderData: {
                // 订单数量
                todayOrderQuantity: 0, yesterdayOrderQuantity: 0, thisMonthOrderQuantity: 0, yesterdayMonthOrderQuantity: 0,
                // 订单金额
                todayOrderAmount: 0, yesterdayOrderAmount: 0, thisMonthOrderAmount: 0, yesterdayMonthOrderAmount: 0,
            },
            consumeProgressData: {},
            extensionProgressData: {},
            fundProgressData: {},
            consumeRadioSelect: 'today',
            extensionRadioSelect: 'today',
            fundRadioSelect: 'today',
            integralRadioSelect: 0,
            queryDay: 7,
            // 折线图
            lineOptions: {
                grid: {
                    right: '0',
                    // left: '5%',
                    bottom: '25',
                },
                tooltip: {
                    trigger: 'axis',
                    axisPointer: {
                        type: 'cross',
                        label: {
                            backgroundColor: '#6a7985'
                        }
                    }
                },
                legend: {
                    right: '0',
                    top: '20',
                    data: []
                },
                xAxis: {
                    type: 'category',
                    data: []
                },
                yAxis: {
                    type: 'value'
                },
                series: [
                    {
                        type: 'line',
                        name: "",
                        smooth: true,
                        emphasis: {
                            focus: 'series',
                            blurScope: 'coordinateSystem'
                        },
                        areaStyle: {
                            color: {
                                type: 'linear',
                                x: 0,
                                y: 0,
                                x2: 0,
                                y2: 1,
                                colorStops: [{
                                    offset: 0, color: '#1890FF' // 0% 处的颜色
                                }, {
                                    offset: 1, color: '#FFFFFF' // 100% 处的颜色
                                }],
                                global: false // 缺省为 false
                            }
                        },
                        data: []
                    },
                ]

            },
            // 折线+柱状图
            lineAndBarOptions: {
                grid: {
                    right: '10',
                    // left: '5%',
                    bottom: '25',
                },
                tooltip: {
                    trigger: 'axis',
                    axisPointer: {
                        type: 'cross',
                        label: {
                            backgroundColor: '#6a7985'
                        }
                    },
                    formatter: function (params) {
                        var relVal = params[0].name;
                        for (var i = 0, l = params.length; i < l; i++) {
                            relVal += '<br/>' + params[i].marker + params[i].seriesName + ' : ' + params[i].value / 100 + (params[i].seriesName == '成交额' ? '百元' : '')
                        }
                        return relVal;
                    }
                },
                color: ['#1890FF', '#FDAA33'],
                legend: {
                    right: '0',
                    top: '20',
                    data: ['成交额', '成交量']
                },
                xAxis: {
                    type: 'category',
                    data: []
                },
                yAxis: {
                    type: 'value'
                },
                series: [
                    {
                        name: '成交额',
                        type: 'bar',
                        emphasis: {
                            focus: 'series',
                            blurScope: 'coordinateSystem'
                        },
                        data: []
                    },
                    {
                        type: 'line',
                        name: "成交量",
                        smooth: true,
                        symbol: 'none',
                        emphasis: {
                            focus: 'series',
                            blurScope: 'coordinateSystem'
                        },
                        areaStyle: {
                            color: {
                                type: 'linear',
                                x: 0,
                                y: 0,
                                x2: 0,
                                y2: 1,
                                colorStops: [{
                                    offset: 0, color: '#FFEED6' // 0% 处的颜色
                                }, {
                                    offset: 1, color: '#FFFFFF' // 100% 处的颜色
                                }],
                                global: false // 缺省为 false
                            }
                        },
                        data: []
                    },
                ]

            },
        }
    },
    async mounted() {
        await loadBMap('2MT9DIRpr8GpcA5q1BFtM2G0WfIG4MnD') // 加载引入BMap
        this.initMap()
        let _this = this
        window.onresize = () => {
            clearTimeout(this.timer)
            this.timer = setTimeout(() => {
                _this.lineChart && _this.lineChart.resize();
                _this.lineAndBarChart && _this.lineAndBarChart.resize();
            }, 300)
        };
    },
    components: {
    },
    watch: {
        queryDay() {
            this.orderTransactionKLineInfo()
        },
        integralRadioSelect() {
            this.pointsConversionKLineInfo()
        },
        queryTime: {
            handler(newV, oldValue) {
                if (newV && newV.length > 0) {
                    this.queryData.startTime = newV[0] + ' 00:00:00'
                    this.queryData.endTime = newV[1] + ' 23:59:59'
                    // this.getdataFun()
                } else {
                    delete this.queryData.startTime
                    delete this.queryData.endTime
                }
            }
        },
    },
    computed: {
        getTodayOrder() {
            let num = this.orderData.todayOrderQuantity / this.orderData.thisMonthOrderQuantity * 100
            return num || 0
        },
        getConsumeProgress() {
            if (this.consumeRadioSelect == 'yesterday') {
                return this.consumeProgressData.yesterdayProgress
            } else if (this.consumeRadioSelect == 'today') {
                return this.consumeProgressData.todayProgress
            } else {
                return 0
            }
        },
        getExtensionProgress() {
            if (this.extensionRadioSelect == 'yesterday') {
                return this.extensionProgressData.yesterdayProgress
            } else if (this.extensionRadioSelect == 'today') {
                return this.extensionProgressData.todayProgress
            } else {
                return 0
            }
        },
        getFundProgress() {
            if (this.fundRadioSelect == 'yesterday') {
                return this.fundProgressData.yesterdayProgress
            } else if (this.fundRadioSelect == 'today') {
                return this.fundProgressData.todayProgress
            } else {
                return 0
            }
        },
        // getIntegralRadioText() {
        //     switch (this.integralRadioSelect) {
        //         case 'consume':
        //             return '消费积分'
        //         case 'extension':
        //             return '推广积分'
        //         case 'merchant':
        //             return '商家积分'
        //         case 'education':
        //             return '教育基金'
        //     }
        // }
    },
    created() {
        let _this = this
        // this.orderStatistics()
        // this.memberStatistics()
        // this.pointsConversionKLineInfo()
        // this.orderTransactionKLineInfo()
        // setTimeout(() => {
        //     _this.integralStatistics()
        // }, 1000);
		this.schoolInfo()
console.log("进来住")
        // this.exportExcel()

    },
    // mounted() {
    //     let _this = this
    //     window.onresize = () => {
    //         clearTimeout(this.timer)
    //         this.timer = setTimeout(() => {
    //             _this.lineChart && _this.lineChart.resize();
    //             _this.lineAndBarChart && _this.lineAndBarChart.resize();
    //         }, 300)
    //     };
    // },
    activated() {

    },
    deactivated() {

    },
    methods: {
        // 初始化地图
        initMap() {
            var that = this
            console.log("666")
            // 1、挂载地图
            this.map = new BMap.Map('map-container', { enableMapClick: false })
            var point = new BMap.Point(113.3324436, 23.1315381)
            this.map.centerAndZoom(point, 19)

            // 3、设置图像标注并绑定拖拽标注结束后事件
            this.mk = new BMap.Marker(point, { enableDragging: true })
            this.map.addOverlay(this.mk)
            this.mk.addEventListener('dragend', function (e) {
                that.getAddrByPoint(e.point)
            })

            // 4、添加（右上角）平移缩放控件
            this.map.addControl(new BMap.NavigationControl({ anchor: BMAP_ANCHOR_TOP_RIGHT, type: BMAP_NAVIGATION_CONTROL_SMALL }))

            // 5、添加（左下角）定位控件
            var geolocationControl = new BMap.GeolocationControl({ anchor: BMAP_ANCHOR_BOTTOM_LEFT })
            geolocationControl.addEventListener('locationSuccess', function (e) {
                that.getAddrByPoint(e.point)
            })
            geolocationControl.addEventListener('locationError', function (e) {
                alert(e.message)
            })
            this.map.addControl(geolocationControl)

            // 6、浏览器定位
            // this.geolocation()

            // 7、绑定点击地图任意点事件
            this.map.addEventListener('click', function (e) {
                that.getAddrByPoint(e.point)
            })
        },
        // 获取两点间的距离
        getDistancs(pointA, pointB) {
            return this.map.getDistance(pointA, pointB).toFixed(2)
        },
        // 浏览器定位函数
        geolocation() {
            var that = this
            var geolocation = new BMap.Geolocation()
            geolocation.getCurrentPosition(function (res) {
                if (this.getStatus() == BMAP_STATUS_SUCCESS) {
                    that.getAddrByPoint(res.point)
                    that.locationPoint = res.point
                } else {
                    // alert('failed' + this.getStatus())
                    that.locationPoint = new BMap.Point(113.3324436, 23.1315381)
                }
            }, { enableHighAccuracy: true })
        },
        // 2、逆地址解析函数
        getAddrByPoint(point) {
            var that = this
            var geco = new BMap.Geocoder()
            geco.getLocation(point, function (res) {
                console.log(res)
                that.mk.setPosition(point)
                that.map.panTo(point)
                that.form.address = res.address
                that.form.addrPoint = point
            })
        },
        // 8-1、地址搜索
        querySearchAsync(str, cb) {
            var options = {
                onSearchComplete: function (res) {
                    var s = []
                    if (local.getStatus() == BMAP_STATUS_SUCCESS) {
                        for (var i = 0; i < res.getCurrentNumPois(); i++) {
                            s.push(res.getPoi(i))
                        }
                        cb(s)
                    } else {
                        cb(s)
                    }
                }
            }
            var local = new BMap.LocalSearch(this.map, options)
            local.search(str)
        },
        // 8-2、选择地址
        handleSelect(item) {
            this.form.address = item.address + item.title
            this.form.addrPoint = item.point
            this.map.clearOverlays()
            this.mk = new BMap.Marker(item.point)
            this.map.addOverlay(this.mk)
            this.map.panTo(item.point)
        },
        onSubmit() {
            console.log(this.form)
			let data={
				"address": this.form.address,
					"distance": this.form.distance,
					"latitude": this.form.addrPoint.lat,
					"longitude": this.form.addrPoint.lng
			}
			axios({
			    url: "/admin/school/setSchoolAddress",
			    method: "post",
			    data: data,
			}).then(result => {
			    if (result.code == 0) {
			         this.$message.success(result.data.errMsg || '成功');
			    } else {
			        this.$message.error(result.data.errMsg || '失败');
			    }
				})
			
        },
		schoolInfo(){
			var _this = this;
			this.loading = true
			         
			axios({
			    url: "/admin/school/get",
			    method: "post"
			}).then(result => {
				this.info = result.data
				this.form.address=result.data.address
				this.form.distance=result.data.distance
				this.form.addrPoint.lat=result.data.latitude
				this.form.addrPoint.lng=result.data.longitude
				// this.form.address=,
				// 	"distance": this.form.distance,
				// 	"latitude": this.form.addrPoint.lat,
				// 	"longitude": this.form.addrPoint.lng
			    this.loading = false;
			}).catch(err => {
			    this.loading = false;
			})
		},
        // 积分数据
        integralStatistics() {
            this.$apis.integralStatistics().then(res => {
                if (res.resp_code == 0 && res.data) {
                    var {
                        // 消费积分
                        todayReleaseQuantity, yesterdayReleaseQuantity, unreleasedQuantity,
                        // 推广积分
                        todayOutputQuantity, yesterdayOutputQuantity, totalOutputQuantity,
                        // 教育基金
                        todayConversionQuantity, yesterdayConversionQuantity, totalConversionQuantity,
                    } = res.data
                    this.consumeProgressData = {
                        todayReleaseQuantity, yesterdayReleaseQuantity, unreleasedQuantity,
                        todayProgress: todayReleaseQuantity / unreleasedQuantity * 100 || 0,
                        yesterdayProgress: yesterdayReleaseQuantity / unreleasedQuantity * 100 || 0
                    }
                    this.extensionProgressData = {
                        todayOutputQuantity, yesterdayOutputQuantity, totalOutputQuantity,
                        todayProgress: todayOutputQuantity / totalOutputQuantity * 100 || 0,
                        yesterdayProgress: yesterdayOutputQuantity / totalOutputQuantity * 100 || 0
                    }
                    this.fundProgressData = {
                        todayConversionQuantity, yesterdayConversionQuantity, totalConversionQuantity,
                        todayProgress: todayConversionQuantity / totalConversionQuantity * 100 || 0,
                        yesterdayProgress: yesterdayConversionQuantity / totalConversionQuantity * 100 || 0
                    }
                }
            })
        },
        // 消费积分文字
        consumeText() {
            var { todayReleaseQuantity, yesterdayReleaseQuantity } = this.consumeProgressData
            let text = this.consumeRadioSelect == 'today' ? todayReleaseQuantity : yesterdayReleaseQuantity
            return text && text || '0'
        },
        // 推广积分文字
        extensionText() {
            var { todayOutputQuantity, yesterdayOutputQuantity } = this.extensionProgressData
            let text = this.extensionRadioSelect == 'today' ? todayOutputQuantity : yesterdayOutputQuantity
            return text && text || '0'
        },
        // 教育基金文字
        fundText() {
            var { todayConversionQuantity, yesterdayConversionQuantity } = this.fundProgressData
            let text = this.fundRadioSelect == 'today' ? todayConversionQuantity : yesterdayConversionQuantity
            return text && text || '0'
        },
        // orderStatistics() {
        //     this.$apis.orderStatistics().then(res => {
        //         if (res.resp_code == 0 && res.data) {
        //             this.orderData = res.data

        //         }
        //     })
        // },
        // memberStatistics() {
        //     this.$apis.memberStatistics().then(res => {
        //         if (res.resp_code == 0 && res.data) {
        //             this.memberAndUserData = res.data
        //         }
        //     })
        // },
        pointsConversionKLineInfo() {
            this.$apis.pointsConversionKLineInfo(this.integralRadioSelect).then(res => {
                if (res.resp_code == 0 && res.data) {
                    this.lineChart = echarts.init(document.getElementById('lineChart'), mytheme);
                    let Xdata = []
                    let Ydata = []
                    //折线图
                    res.data.forEach(ele => {
                        Xdata.push(ele.dateTime.slice(-4))
                        Ydata.push(ele.usageQuantity)
                    });
                    this.lineOptions.xAxis.data = Xdata
                    this.lineOptions.series[0].data = Ydata
                    this.lineChart.setOption(this.lineOptions)
                }
                this.integralLoading = false
            }).catch(err => {
                this.integralLoading = false
            })
        },
        orderTransactionKLineInfo() {
            this.$apis.orderTransactionKLineInfo(this.queryDay).then(res => {
                if (res.resp_code == 0 && res.data) {
                    this.lineAndBarChart = echarts.init(document.getElementById('lineAndBarChart'), mytheme);
                    let Xdata = []
                    let Ydata1 = []
                    let Ydata2 = []
                    //折线图
                    res.data.forEach(ele => {
                        Xdata.push(ele.dateTime.slice(-4))
                        Ydata1.push(ele.orderAmount / 100)
                        Ydata2.push(ele.orderCount)
                    });
                    //折线、柱形图
                    this.lineAndBarOptions.xAxis.data = Xdata
                    this.lineAndBarOptions.series[0].data = Ydata1
                    this.lineAndBarOptions.series[1].data = Ydata2
                    this.lineAndBarChart.setOption(this.lineAndBarOptions)
                }
                this.orderTransactionLoading = false
            }).catch(err => {
                this.orderTransactionLoading = false
            })
        },
        onClickItem(index) {
            this.curNow = index;
        },
        changeDate() {
            const now = new Date().getTime();
            this.data.forEach((item, index) => {
                const date = new Date(now - (6 - index) * 86400000);
                item.name = `${date.getFullYear()}/${date.getMonth() + 1}/${date.getDate()}`;
            });
        },
    }
};
</script>


<style lang="scss" scoped>
.top_box {
    // margin-bottom: 15px;
}

.top-card-title {
    font-size: 16px;
    color: #333;
    font-weight: 600;
}
.top-card-title2 {
    margin-left: 10px;
    font-size: 12px;
    color: #999;
}
.top-card-footer {
    margin-top: 25px;
    .top-card-img {
        margin-right: 15px;
        width: 56px;
        height: 56px;
    }
    .progress-box {
        font-size: 20px;
        color: #333;
        font-weight: bold;
        flex: 1;
        p {
            font-size: 14px;
            color: #333;
            margin: 3px 0;
            span:nth-of-type(2) {
                float: right;
            }
        }
        p:nth-of-type(2) {
            margin-top: 10px;
        }
    }
}
.circle-progress-box {
    padding: 45px 0;
    border-bottom: 1px solid #eeeeee;
}
.footer-text {
    padding-top: 15px;
    font-size: 14px;
    color: #999;
    text-align: center;
}
::v-deep {
    .el-card {
        border: 0;
        min-height: 155px;
        border-radius: 16px;
        max-height: 356px;
    }
    .el-card__body {
        padding: 15px 20px;
    }
    .consume-progress {
        .el-progress__text {
            color: #1890ff;
        }
    }
    .extension-progress {
        .el-progress__text {
            color: #2fc25b;
        }
    }
    .fund-progress {
        .el-progress__text {
            color: #6d5aff;
        }
    }
}
.progress-box2 {
    padding-bottom: 20px;
    border-bottom: 0;
}
.fenyong_text {
    margin: 10px 0;
    color: #1b93f8;
    font-size: 14px;
}
.fenyong_text2 {
    color: #999;
    font-size: 14px;
}
.el-col {
    margin-top: 25px;
}
.autoAddressClass {
    li {
        i.el-icon-search {
            margin-top: 11px;
        }
        .mgr10 {
            margin-right: 10px;
        }
        .title {
            text-overflow: ellipsis;
            overflow: hidden;
        }
        .address {
            line-height: 1;
            font-size: 12px;
            color: #b4b4b4;
            margin-bottom: 5px;
        }
    }
}
</style>
